package com.shengdong.water.feature.qrcode

import com.alibaba.android.arouter.facade.annotation.Route
import com.google.zxing.Result
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.hjq.toast.Toaster
import com.king.camera.scan.AnalyzeResult
import com.king.camera.scan.CameraScan
import com.king.camera.scan.analyze.Analyzer
import com.king.view.viewfinderview.ViewfinderView
import com.king.zxing.BarcodeCameraScanActivity
import com.king.zxing.DecodeConfig
import com.king.zxing.DecodeFormatManager
import com.king.zxing.analyze.QRCodeAnalyzer
import com.shengdong.water.R
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.router.RouterManager
import dagger.hilt.android.AndroidEntryPoint

@Route(path = RouterConfig.QRCODE_SCAN_PATH)
@AndroidEntryPoint
class QrcodeScanActivity: BarcodeCameraScanActivity()  {


    override fun getLayoutId() = R.layout.activity_qrcode_scan


    override fun initUI() {
        super.initUI()
        findViewById<TitleBar>(R.id.title_bar).setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }

        })
        // 设置取景框样式
//        viewfinderView.setViewfinderStyle(ViewfinderView.ViewfinderStyle.CLASSIC)
    }

    override fun initCameraScan(cameraScan: CameraScan<Result>) {
        super.initCameraScan(cameraScan)
        // 根据需要设置CameraScan相关配置
        cameraScan.setPlayBeep(true)
    }

    override fun createAnalyzer(): Analyzer<Result> {
        // 初始化解码配置
        val decodeConfig = DecodeConfig().apply {
            // 如果只有识别二维码的需求，这样设置效率会更高，不设置默认为DecodeFormatManager.DEFAULT_HINTS
            hints = DecodeFormatManager.QR_CODE_HINTS
            // 设置是否全区域识别，默认false
            isFullAreaScan = true
            isSupportVerticalCode = true
            isSupportLuminanceInvert = true
            areaRectRatio = 0.8f
            areaRectVerticalOffset = 0
            areaRectHorizontalOffset = 0
        }
        // BarcodeCameraScanActivity默认使用的MultiFormatAnalyzer，这里可以改为使用QRCodeAnalyzer
        return QRCodeAnalyzer(decodeConfig)
    }



    override fun onScanResultCallback(result: AnalyzeResult<Result>) {
        // 停止分析
        cameraScan.setAnalyzeImage(false)
        //显示结果
        if(result.result.text.contains("http") || result.result.text.contains("https")){
            RouterManager.build(RouterConfig.WEB_PATH)
                .withString("webUrl", result.result.text)
                .navigate()
            return
        }
        Toaster.show(result.result.text)
        finish()

    }
}